import java.util.*;


public class code4_2 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param board string字符串一维数组
     * @param word string字符串
     * @return bool布尔型
     */
    int m;
    int n;
    int[] dx = {0, 0, -1, 1};
    int[] dy = {1, -1, 0, 0};
    boolean[][] visit;
    public boolean exist (String[] board, String word) {
        m = board.length;
        n = board[0].length();
        visit = new boolean[m][n];
        char[][] boards = new char[m][n];
        for (int i = 0; i < m; i++) {
            boards[i] = board[i].toCharArray();
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (boards[i][j] == word.charAt(0)) {
                    visit[i][j] = true;
                    if (dfs(boards, i, j, word, 1)) {
                        return true;
                    }
                    //回溯
                    visit[i][j] = false;
                }
            }
        }
        return false;
    }

    public boolean dfs(char[][] boards, int x, int y, String word, int count) {
        if (word.length() == count) return true;

        for (int k = 0; k < 4; k++) {
            int nx = x + dx[k];
            int ny = y + dy[k];
            //标记

            if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visit[nx][ny] &&
                    word.charAt(count) == boards[nx][ny]) {
                visit[nx][ny] = true;
                if(dfs(boards, nx, ny, word, count + 1)) return true;
                //回溯
                visit[nx][ny] = false;
            }

        }
        return false;
    }
}